/**************************
 * URL Mappings
 **************************/

model.homeAction = function() {
	presenter.setTitle("SBIExam :: Welcome, enter key");
	presenter.setHeading("Enter Examination Key");
	presenter.showView ("enterkey.html");
}

model.examkeyAction = function() {
	model.submitExamCode();
}

model.prepareAction = function() {
	presenter.setTitle("SBIExam :: Welcome, prepare to write");
	presenter.setHeading("Prepare to Write");
	presenter.showView ("prepare.html");
}

model.writeAction = function() {
	presenter.setTitle("SBIExam :: Exam in progress");
	presenter.setHeading("Examination in Progress");
	presenter.showView ("write.html");
}

model.passAction = function() {
	presenter.setTitle("SBIExam :: Congratulations, you passed");
	presenter.setHeading("Congratulations, you passed");
	presenter.showView ("pass.html");
}

model.failAction = function() {
	presenter.setTitle("SBIExam :: Bad luck, you failed");
	presenter.setHeading("Fail");
	presenter.showView ("fail.html");
}

/**************************
 * 404 Action
 **************************/

model.pageNotFoundAction = function() {
	presenter.setTitle("Page Not Found");
	presenter.setHeading ("Page Not Found");
	presenter.show404 ("404.html");
}

/**************************
 * BUSINESS LOGIC
 **************************/

model.submitExamCode = function() {

	var examkey = model.formData['examkey'];

	if (examkey.length > 3) {

		var data = {
			'method': 'examkey',
			'examkey' : model.formData['examkey']
		}

		var fn_success = function(json) {
			controller.debug(json);
			controller.debug ("Authentication Request Successful");

			try {
				var authenticated = json.authenticated;
				if (authenticated == "true") {
					controller.log ("authenticated");
					controller.relocateTo("#/prepare");
				} else {
					presenter.setModalContent("<h2>Invalid Exam Key</h2><p>Examkey " + json.examkey + " is invalid, has been already used, or has expired.</p><a href=\"javascript:window.presenter.hideModal()\">Close</a>");
					presenter.showModal();
					controller.relocateTo("#/");
				}
			} catch (error) {
				controller.log ("SbiExam Error: " + error);
				controller.relocateTo("#/");
			}

		}

		model.fetchData ('/service/authenticate', data, fn_success);

	} else {
		model.addError("Please enter a valid exam key");
		controller.relocateTo("#/");
	}


}